<script setup lang="ts">
import { ref } from 'vue';
import { NModal, NCard, NSpace, NButton, NSelect, NDescriptions, NDescriptionsItem, NTag, NTable, NSpin, NAlert } from 'naive-ui';
import { analyzeImpact, type ImpactAnalysisDTO } from '@/service/api/dataplatform/metadata';

const visible = ref(false);
const loading = ref(false);
const tableId = ref<number>(0);
const changeType = ref('STRUCTURE_CHANGE');
const analysisResult = ref<ImpactAnalysisDTO | null>(null);

// 变更类型选项
const changeTypeOptions = [
  { label: '结构变更', value: 'STRUCTURE_CHANGE' },
  { label: '删除表', value: 'DELETE' },
  { label: '重命名', value: 'RENAME' }
];

// 受影响任务列定义
const taskColumns = [
  { title: '任务ID', key: 'taskId', width: 100 },
  { title: '任务名称', key: 'taskName', ellipsis: { tooltip: true } },
  { title: '任务类型', key: 'taskType', width: 120 },
  {
    title: '影响类型',
    key: 'impactType',
    width: 120,
    render: (row: any) => h(NTag, { type: 'warning' }, { default: () => row.impactType })
  }
];

// 受影响API列定义
const apiColumns = [
  { title: 'API ID', key: 'apiId', width: 100 },
  { title: 'API名称', key: 'apiName', ellipsis: { tooltip: true } },
  { title: 'API路径', key: 'apiPath', ellipsis: { tooltip: true } },
  {
    title: '影响类型',
    key: 'impactType',
    width: 120,
    render: (row: any) => h(NTag, { type: 'warning' }, { default: () => row.impactType })
  }
];

// 影响级别标签类型
function getImpactLevelType(level: string) {
  switch (level) {
    case 'LOW':
      return 'success';
    case 'MEDIUM':
      return 'warning';
    case 'HIGH':
      return 'error';
    default:
      return 'default';
  }
}

// 影响级别文本
function getImpactLevelText(level: string) {
  switch (level) {
    case 'LOW':
      return '低';
    case 'MEDIUM':
      return '中';
    case 'HIGH':
      return '高';
    default:
      return level;
  }
}

// 打开弹窗
async function open(id: number) {
  tableId.value = id;
  visible.value = true;
  await performAnalysis();
}

// 执行分析
async function performAnalysis() {
  loading.value = true;
  try {
    const { data } = await analyzeImpact({
      tableId: tableId.value,
      changeType: changeType.value
    });
    analysisResult.value = data;
  } catch (error) {
    console.error('影响分析失败:', error);
  } finally {
    loading.value = false;
  }
}

// 变更类型改变
function handleChangeTypeChange() {
  performAnalysis();
}

// 关闭弹窗
function close() {
  visible.value = false;
  analysisResult.value = null;
  changeType.value = 'STRUCTURE_CHANGE';
}

defineExpose({ open, close });
</script>

<template>
  <NModal
    v-model:show="visible"
    preset="card"
    title="影响分析"
    :style="{ width: '90%', maxWidth: '1000px' }"
    :segmented="{ content: true }"
  >
    <NSpace vertical :size="16">
      <!-- 控制栏 -->
      <NSpace align="center">
        <span>变更类型:</span>
        <NSelect
          v-model:value="changeType"
          :options="changeTypeOptions"
          style="width: 200px"
          @update:value="handleChangeTypeChange"
        />
        <NButton type="primary" @click="performAnalysis">
          <icon-ic-round-analytics class="mr-4px text-16px" />
          重新分析
        </NButton>
        <NButton @click="close">关闭</NButton>
      </NSpace>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center h-400px">
        <NSpin size="large" />
      </div>

      <!-- 分析结果 -->
      <div v-else-if="analysisResult" class="space-y-16px">
        <!-- 影响概览 -->
        <NAlert :type="getImpactLevelType(analysisResult.impactLevel)" :title="`影响级别: ${getImpactLevelText(analysisResult.impactLevel)}`">
          {{ analysisResult.impactDescription }}
        </NAlert>

        <!-- 基本信息 -->
        <NCard title="基本信息" size="small">
          <NDescriptions :column="2" label-placement="left">
            <NDescriptionsItem label="表名">{{ analysisResult.tableName }}</NDescriptionsItem>
            <NDescriptionsItem label="变更类型">
              <NTag>{{ changeTypeOptions.find(o => o.value === analysisResult.changeType)?.label }}</NTag>
            </NDescriptionsItem>
            <NDescriptionsItem label="上游依赖数">
              <NTag type="info">{{ analysisResult.upstreamCount }}</NTag>
            </NDescriptionsItem>
            <NDescriptionsItem label="下游影响数">
              <NTag type="warning">{{ analysisResult.downstreamCount }}</NTag>
            </NDescriptionsItem>
          </NDescriptions>
        </NCard>

        <!-- 受影响的任务 -->
        <NCard title="受影响的任务" size="small">
          <template #header-extra>
            <NTag type="warning">{{ analysisResult.affectedTasks?.length || 0 }} 个</NTag>
          </template>
          <NTable
            v-if="analysisResult.affectedTasks && analysisResult.affectedTasks.length > 0"
            :columns="taskColumns"
            :data="analysisResult.affectedTasks"
            :max-height="300"
          />
          <NEmpty v-else description="暂无受影响的任务" />
        </NCard>

        <!-- 受影响的API -->
        <NCard title="受影响的API" size="small">
          <template #header-extra>
            <NTag type="warning">{{ analysisResult.affectedApis?.length || 0 }} 个</NTag>
          </template>
          <NTable
            v-if="analysisResult.affectedApis && analysisResult.affectedApis.length > 0"
            :columns="apiColumns"
            :data="analysisResult.affectedApis"
            :max-height="300"
          />
          <NEmpty v-else description="暂无受影响的API" />
        </NCard>

        <!-- 建议 -->
        <NCard title="变更建议" size="small">
          <NSpace vertical>
            <div v-if="analysisResult.impactLevel === 'HIGH'">
              <NAlert type="error" title="高风险变更">
                <ul class="list-disc pl-20px">
                  <li>建议在非业务高峰期进行变更</li>
                  <li>提前通知所有受影响的任务和API负责人</li>
                  <li>准备回滚方案</li>
                  <li>进行充分的测试验证</li>
                </ul>
              </NAlert>
            </div>
            <div v-else-if="analysisResult.impactLevel === 'MEDIUM'">
              <NAlert type="warning" title="中等风险变更">
                <ul class="list-disc pl-20px">
                  <li>通知受影响的任务和API负责人</li>
                  <li>进行必要的测试验证</li>
                  <li>准备应急预案</li>
                </ul>
              </NAlert>
            </div>
            <div v-else>
              <NAlert type="success" title="低风险变更">
                <ul class="list-disc pl-20px">
                  <li>可以正常进行变更</li>
                  <li>建议进行基本的功能测试</li>
                </ul>
              </NAlert>
            </div>
          </NSpace>
        </NCard>
      </div>
    </NSpace>
  </NModal>
</template>

<style scoped>
/* 添加必要的样式 */
</style>
